<?php

namespace App\Repositories\Eloquent;

use App\Models\PolicyUpload;
use App\Repositories\Contracts\QnPolicyInterface;
use App\Services\PolicyUpload\QnService;
use Curl\StrService\StrService;
use MakeRep\Repository;

class QnPolicyRepository extends Repository implements QnPolicyInterface
{

    public $view = 'qnpolicy';
    public $fillable = ['admin_id','policy_id','policy_code','airline','platform','flight_code','share_flight_code','depart_city_code','arrived_city_code','depart_at','cabin','price','seat','show','status','ext','upload_status','upload_msg'];

    function model()
    {
        return PolicyUpload::class;
    }

    public function create($param)
    {

        //组装数据
        QnService::QnDataSet($param);

        //平台上传
        switch ($param['platform']){

            case 30: {
                $param['type']          = 'STOCK';
                break;
            }
            case 31:{
                $param['type']          = 'SINGLE';
                break;
            }
            case 33:{
                $param['type']          = 'ROUND';
                break;
            }
        }


        $param['ext']           = StrService::uuid();
        //处理数据
        $param['supportCba']    = '是';
        //先保存数据等待回调
        $res = $this->savePolicy($param,null);

        if (!empty($res)) {

            $param['policycode'] .= '_'.$res['id'];

            $specialPolicyInterface = resolve('App\Repositories\Ota\Qn\Policy\Contracts\QuPolicyInterface');
            $uploadRes = $specialPolicyInterface->add([$param]);

            if (!empty($uploadRes)){
                $result = str_replace(["\n","\""], ["",""], $uploadRes);
                if (empty($result)) {
                    return true;
                } else {
                    return $result;
                }
            }
        }

        return '网络有问题，稍后重试';
    }

    /**
     * 去哪修改单程统一库存政策
     * @param $param
     * @return mixed
     */
    public function updatePolicy($param)
    {
        // 先删除
        $deletePolicy = $this->deletePolicy($param);

        if (!empty($deletePolicy)){
            $result = str_replace(["\n","\""], ["",""], $deletePolicy);
            if (empty($result)) {
                // 删除成功，再上传政策
                $param['id'] = null;
                return $this -> create($param);
            } else {
                return $result;
            }
        }
    }

    /**
     * 去哪删除
     * @param $param
     * @return mixed
     */
    public function deletePolicy($param){

        $policy = $this->findById($param['id']);


        //平台上传
        switch ($param['platform']) {

            case 30:
            {

                $data = [
                    'type'              => 'STOCK',
                    'airline'           => $policy['airline'],
                    'ext'               => $policy['ext'],
                        'flights' =>[
                        [
                            'type'              => 'STOCK',
                            'airline'           => $policy['airline'],
                            'dpt'               => $policy['depart_city_code'],
                            'arr'               => $policy['arrived_city_code'],
                            'flight_code'       => $policy['flight_code'],
                            'policyCode'        => $policy['policy_code'].'_'.$param['id']
                        ]
                    ],
                ];
                QnService::QnDataSet($data);

                $specialPolicyInterface = resolve('App\Repositories\Ota\Qn\Policy\Contracts\QuPolicyInterface');
                $uploadRes = $specialPolicyInterface->delete($data);
                return $uploadRes;
            }

            case 31:
            {

                $data = [
                    'type'              => 'SINGLE',
                    'airline'           => $policy['airline'],
                    'ext'               => $policy['ext'],
                    'flights' =>[
                        [
                            'type'              => 'SINGLE',
                            'airline'           => $policy['airline'],
                            'dpt'               => $policy['depart_city_code'],
                            'arr'               => $policy['arrived_city_code'],
                            'flight_code'       => $policy['flight_code'],
                            'policyCode'        => $policy['policy_code'].'_'.$param['id']
                        ]
                    ],
                ];
                QnService::QnDataSet($data);

                $specialPolicyInterface = resolve('App\Repositories\Ota\Qn\Policy\Contracts\QuPolicyInterface');
                $uploadRes = $specialPolicyInterface->delete($data);
                return $uploadRes;
            }
        }

        return false;
    }

    /**
     * 保存政策
     * @param $param
     * @param $uploadRes
     * @return void
     */
    private function savePolicy($param,$policyId){

        $data = [
            'admin_id'              => $param['admin']['id'],
//                    'policy_id'             => $policyId,
            'airline'               => $param['flightcode'],
            'policy_code'           => $param['policycode'],
            'platform'              => $param['platform'],
            'flight_code'           => $param['flightcondition'],
            'depart_city_code'      => $param['dpt'],
            'arrived_city_code'     => $param['arr'],
            'depart_at'             => $param['startdate'],
            'cabin'                 => $param['cabin'],
            'price'                 => $param['printsource'] == '指定票面价' ? $param['printprice'] : $param['minPrintPrice'],
            'ext'                   => $param['ext'],
            'upload_status'         => 1,
        ];

        $dataQn = [
            'act_carrier'	            => $param['actCarrier'],
            'arrived_at'                => $param['enddate'],
            'depart_date_forbid'	    => $param['dptDateForbid'],
            'depart_time_slot'	        => $param['depttimeslot'],
            'day_condition'	            => !empty($param['dayCondition']) ? implode('',$param['dayCondition']) : '1234567',
            'forbid_airlines'	        => $param['forbidAirlines'],
            'no_cabin'	                => $param['forbidCabin'],
            'flight_no_limit'	        => $param['flightNoLimit'],
            'flight_condition'	        => $param['flightcondition'],
            'shared'	                => $param['shared'],
            'stop'	                    => !empty($value['stop']) ? $value['stop'] : '是',
            'product_mark'	            => implode(',',$param['productMark']),
            'sale_start_at'	            => $param['saledatestart'],
            'sale_end_at'	            => $param['saledateend'],
            'sale_forbid_start_at'	    => $param['saleDateForbidStart'],
            'sale_forbid_end_at'	    => $param['saleDateForbidEnd'],
            'sale_time_slot'	        => $param['saleTimeSlot'],
            'lock_time'	                => $param['lockTime'],
            'earliest_before_ticket'    => $param['earliestBeforeTicket'],
            'before_ticket'             => $param['beforeTicket'],
            'card_type'	                => $param['cardtype'],
            'support_cba'	            => $param['supportCba'],
            'print_source'	            => $param['printsource'],
            'print_compute_type'	    => $param['printComputeType'],
            'x_cabin'	                => $param['xCabin'],
            'select_type'	            => !empty($param['selectType']) ? $param['selectType'] : '取低',
            'print_return_point'	    => !empty($param['printReturnPoint']) ? $param['printReturnPoint'] : 0,
            'print_return_price'	    => !empty($param['printReturnPrice']) ? $param['printReturnPrice'] : 0,
            'x_price_type'	            => !empty($param['xPriceType']) ? $param['xPriceType'] : '十位四舍五入',
            'min_print_price'	        => !empty($param['minPrintPrice']) ? $param['minPrintPrice'] : 0,
            'max_print_price'	        => !empty($param['maxPrintPrice']) ? $param['maxPrintPrice'] : 0,
            'policy_return_point'	    => $param['policyReturnPoint'],
            'policy_return_price'	    => $param['policyReturnPrice'],
            'auto_price_threshold'	    => $param['autoPriceThreshold'],
            'percent_price_threshold'   => $param['percentPriceThreshold'],
            'pre_office_no'             => $param['preOfficeNo'],
            'need_pnr'	                => $param['needPnr'],
            'high_demand_type'	        => $param['highDemandType'],
            'high_demand_threshold'	    => $param['highDemandThreshold'],
            'office_no'	                => $param['officeNo'],
            'need_pata'	                => $param['needPata'],
            'return_rule'	            => $param['returnRule'],
            'change_rule'	            => $param['changeRule'],
            'endorsement'	            => isset($param['endorsement']) ? $param['endorsement'] : '否',
            'policy_type'	            => $param['type'],
            'is_back'	                => 0,
            'max_stock'	                => !empty($param['maxStock']) ? $param['maxStock'] : 9,
            'remain_stock'	            => !empty($param['maxStock']) ? $param['maxStock'] : 9,
            'cabin_dec'	                => $param['cabinNote'],
        ];

        $status = $param['status'];
        if ($status == '删除') {
            $data['status'] = -1;
        } else if ($status == '挂起') {
            $data['status'] = 0;
        } else if ($status == '有效') {
            $data['status'] = 1;
        } else if ($status == '失效') {
            $data['status'] = 2;
        } else if ($status == '待确认') {
            $data['status'] = 3;
        }

        switch ($param['platform']){
            case 30:
            {

                $data['seat'] = $param['maxStock'] ;
                $dataQn['inventory_type'] = $param['InventoryType'] == 'FIX' ? 1 : 2;
                break;
            }
            default: break;
        }
        $policyUploadQnInterface = resolve('App\Repositories\Contracts\PolicyUploadQnInterface');

        if (empty($param['id'])) {

            $res = $this->add($data);

            $dataQn['policy_upload_id'] = $res['id'];
            $resQn = $policyUploadQnInterface->add($dataQn);
        } else {
            $res = $this->update(['id'=>$param['id']],$data);

            $resQn = $policyUploadQnInterface->update(['id'=>$param['policyDetailId']],$dataQn);
        }

        return $res;
    }


    /**
     * 往返政策保存第二程
     * @param $param
     * @param $uploadRes
     * @return void
     */
    public function saveSecondPolicy($param){

        $data = [
            'admin_id'              => $param['admin']['id'],
            'policy_upload_id'      => $param['policy_upload_id'],
            'airline'               => $param['flightcode2'],
            'policy_code'           => $param['policycode'],
            'platform'              => $param['platform'],
            'flight_code'           => $param['flightcondition2'],
            'depart_city_code'      => $param['dpt2'],
            'arrived_city_code'     => $param['arr2'],
            'depart_at'             => $param['startdate2'],
            'cabin'                 => $param['cabin2'],
            'price'                 => $param['printsource2'] == '指定票面价' ? $param['printprice2'] : $param['minPrintPrice2'],
            'ext'                   => $param['ext'],
            'upload_status'         => 1,
        ];

        $dataQn = [
            //'act_carrier'	            => $param['actCarrier'],
            'arrived_at'                => $param['enddate2'],
            'depart_date_forbid'	    => $param['dptDateForbid2'],
            'depart_time_slot'	        => $param['depttimeslot'],
            'day_condition'	            => !empty($param['dayCondition2']) ? implode('',$param['dayCondition2']) : '1234567',
            'forbid_airlines'	        => $param['forbidAirlines2'],
            'no_cabin'	                => $param['forbidCabin2'],
            'flight_no_limit'	        => $param['flightNoLimit2'],
            'flight_condition'	        => $param['flightcondition2'],
            'shared'	                => $param['shared2'],
            'stop'	                    => !empty($value['stop2']) ? $value['stop2'] : '是',
            'product_mark'	            => implode(',',$param['productMark2']),
            'sale_start_at'	            => $param['saledatestart2'],
            'sale_end_at'	            => $param['saledateend2'],
            'sale_forbid_start_at'	    => $param['saleDateForbidStart2'],
            'sale_forbid_end_at'	    => $param['saleDateForbidEnd2'],
            'sale_time_slot'	        => $param['saleTimeSlot2'],
            'lock_time'	                => $param['lockTime2'],
            'earliest_before_ticket'    => $param['earliestBeforeTicket2'],
            'before_ticket'             => $param['beforeTicket2'],
            'card_type'	                => $param['cardtype2'],
            'support_cba'	            => $param['supportCba2'],
            'print_source'	            => $param['printsource2'],
            'print_compute_type'	    => $param['printComputeType2'],
            'x_cabin'	                => $param['xCabin2'],
            'select_type'	            => !empty($param['selectType2']) ? $param['selectType2'] : '取低',
            'print_return_point'	    => !empty($param['printReturnPoint2']) ? $param['printReturnPoint2'] : 0,
            'print_return_price'	    => !empty($param['printReturnPrice2']) ? $param['printReturnPrice2'] : 0,
            'x_price_type'	            => !empty($param['xPriceType2']) ? $param['xPriceType2'] : '十位四舍五入',
            'min_print_price'	        => !empty($param['minPrintPrice2']) ? $param['minPrintPrice2'] : 0,
            'max_print_price'	        => !empty($param['maxPrintPrice2']) ? $param['maxPrintPrice2'] : 0,
            'policy_return_point'	    => $param['policyReturnPoint2'],
            'policy_return_price'	    => $param['policyReturnPrice2'],
            'auto_price_threshold'	    => $param['autoPriceThreshold2'],
            'percent_price_threshold'   => $param['percentPriceThreshold2'],
            'pre_office_no'             => $param['preOfficeNo2'],
            'need_pnr'	                => $param['needPnr2'],
            'high_demand_type'	        => $param['highDemandType2'],
            'high_demand_threshold'	    => $param['highDemandThreshold2'],
            'office_no'	                => $param['officeNo2'],
            'need_pata'	                => $param['needPata2'],
            'return_rule'	            => $param['returnRule2'],
            'change_rule'	            => $param['changeRule2'],
            'endorsement'	            => isset($param['endorsement2']) ? $param['endorsement2'] : '否',
            'policy_type'	            => $param['type'],
            'is_back'	                => 0,
            'max_stock'	                => !empty($param['maxStock2']) ? $param['maxStock2'] : 9,
            'remain_stock'	            => !empty($param['maxStock2']) ? $param['maxStock2'] : 9,
            'cabin_dec'	                => $param['cabinNote'],
        ];

        $status = $param['status'];
        if ($status == '删除') {
            $data['status'] = -1;
        } else if ($status == '挂起') {
            $data['status'] = 0;
        } else if ($status == '有效') {
            $data['status'] = 1;
        } else if ($status == '失效') {
            $data['status'] = 2;
        } else if ($status == '待确认') {
            $data['status'] = 3;
        }

        switch ($param['platform']){
            case 30:
            {

                $data['seat'] = $param['maxStock'] ;
                $dataQn['inventory_type'] = $param['InventoryType'] == 'FIX' ? 1 : 2;
                break;
            }
            default: break;
        }
        $policyUploadQnInterface = resolve('App\Repositories\Contracts\PolicyUploadQnInterface');

        if (empty($param['id'])) {

            $res = $this->add($data);

            $dataQn['policy_upload_id'] = $res['id'];
            $resQn = $policyUploadQnInterface->add($dataQn);
        } else {
            $res = $this->update(['id'=>$param['id']],$data);

            $resQn = $policyUploadQnInterface->update(['id'=>$param['policyDetailId']],$dataQn);
        }

        return $res;
    }

}